const { JWT, ExpressJWT } = require("@util/jwt");

// 中间件，验证 token 和密钥是否正确
module.exports = async (req, res, next, paths = []) => {
  const { authorization = "" } = req.headers;
  const { token: bodyToken } = req.body || {};
  const { token: queryToken } = req.query || {};
  console.log(req.query, [authorization, bodyToken, queryToken].some(_ => !_), [0]);
  if (![authorization, bodyToken, queryToken].some(_ => !_)) {
    // 也可以将数据赋值到 res 对象上
    // res.result = {
    //   code: 401,
    //   msg: "缺少参数~",
    // };
    next({
      code: 401,
      msg: "缺少参数~",
    });
  } else {
    const token = authorization.replace("Bearer ", "");
    try {
      const jwt = new JWT();
      const data = await jwt.verify(token);
      next({
        code: 200,
        data,
        msg: "成功~",
      });
    } catch (error) {
      // TokenExpiredError 令牌过期
      if (error.name === "TokenExpiredError") {
        next({
          code: 208,
          msg: error.message,
        });
      } else {
        next({
          code: 500,
          msg: error.message,
        });
      }
    }
  }
};

// 解析失败
// 如果解析失败，会抛出 UnauthorizedError，可以通过后置中间件来捕获：
